package com.lbjhan.rpc.serializer;

import com.lbjhan.rpc.pojo.User;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JDKSerializer<T> implements ISerializer {
    @Override
    public byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(obj);
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public T deserialize(byte[] bytes, Class clazz) throws IOException, ClassNotFoundException {
        ByteInputStream byteInputStream = new ByteInputStream(bytes, bytes.length);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteInputStream);
        T t = (T)objectInputStream.readObject();
        return t;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        JDKSerializer<User> userJDKSerializer = new JDKSerializer<>();
        byte[] bytes = userJDKSerializer.serialize(new User(1, "tom"));
        System.out.println(bytes.length);
        User user = userJDKSerializer.deserialize(bytes, null);
        System.out.println(user);
        /**
         * 88
         * User(id=1, name=tom)
         */
    }

}
